<script setup lang="ts">
import { getCommunityTagList, getArticleList, likeArticle, cancelLikeArticle } from '@/api/community';
import { getUserInfoById } from '@/api/user';
import { Article } from '@/api/community/type';
import { Tag } from '@/api/system/tag/type';
import { User } from '@/api/user/type';
import { onMounted, Ref, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showSuccessToast, showFailToast } from 'vant';

interface ArticleWithAuthor extends Article {
  user?: User;
}

const router = useRouter();
const communityId = defineModel() as Ref<string>;
const tagList = ref<Tag[]>([]);
const allArticles = ref<ArticleWithAuthor[]>([]);
const active = ref(0);
const loading = ref(true);

const fetchArticles = async (communityId: string) => {
  try {
    loading.value = true;
    
    const articlesRes = await getArticleList(communityId);
    const articles = articlesRes.data || [];
    
    await Promise.all(
      articles.map(async (article: Article) => {
        try {
          const userRes = await getUserInfoById(article.authorId);
          if (userRes.data) {
            (article as ArticleWithAuthor).user = userRes.data;
          }
        } catch (error) {
          console.error('获取用户信息失败:', error);
        }
      })
    );
    
    allArticles.value = articles as ArticleWithAuthor[];
  } catch (error) {
    console.error('加载文章失败:', error);
  } finally {
    loading.value = false;
  }
};

// 根据当前选中的标签筛选文章
const filteredArticles = computed(() => {
  if (tagList.value.length === 0) return [];
  const currentTagId = tagList.value[active.value]?.id;
  if (!currentTagId) return [];
  return allArticles.value.filter(article => article.tagId === currentTagId);
});

onMounted(async () => {
  try {
    const tagRes = await getCommunityTagList(communityId.value);
    tagList.value = tagRes.data as Tag[];
    
    if (communityId.value) {
      await fetchArticles(communityId.value);
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    loading.value = false;
  }
});

const handleTabChange = async (index: number) => {
  active.value = index;
  if (communityId.value) {
    await fetchArticles(communityId.value);
  }
};

const likeDebounce = ref<{[key: string]: {timestamp: number, processing: boolean}}>({});

const handleLikeToggle = async (article: ArticleWithAuthor, event: Event) => {
  event.stopPropagation();
  
  const articleId = article.id;
  const now = Date.now();
  
  if (likeDebounce.value[articleId]) {
    if (likeDebounce.value[articleId].processing) {
      return;
    }
    
    const lastTime = likeDebounce.value[articleId].timestamp;
    if (now - lastTime < 500) {
      showFailToast('操作太频繁，请稍后再试');
      return;
    }
  }
  
  likeDebounce.value[articleId] = {
    timestamp: now,
    processing: true
  };
  
  const originalLiked = article.isLike;
  const originalLikeCount = article.likeCount || '0';
  
  if (originalLiked) {
    article.isLike = false;
    article.likeCount = String(Math.max(0, parseInt(originalLikeCount) - 1));
    // showSuccessToast('已取消点赞');
  } else {
    article.isLike = true;
    article.likeCount = String(parseInt(originalLikeCount) + 1);
    // showSuccessToast('点赞成功');
  }
  
  try {
    if (originalLiked) {
      await cancelLikeArticle(articleId);
    } else {
      await likeArticle(articleId);
    }
  } catch (error: any) {
    article.isLike = originalLiked;
    article.likeCount = originalLikeCount;

    // if (error.response?.data?.code === 4010) {
    //   showFailToast('你已经点赞该文章');
    //   article.isLike = true;
    // } else if (error.response?.data?.code === 4011) {
    //   showFailToast('你已经取消点赞该文章');
    //   article.isLike = false;
    // } else {
    //   showFailToast('操作失败，请稍后重试');
    //   console.error('点赞操作失败:', error);
    // }
  } finally {
    if (likeDebounce.value[articleId]) {
      likeDebounce.value[articleId].processing = false;
    }
  }
};

const navigateToArticleDetail = (articleId: string) => {
  router.push({
    name: 'CommunityArticleDetail',
    params: { id: articleId }
  });
};

const goToComments = (articleId: string, event: Event) => {
  event.stopPropagation();
  router.push({
    name: 'CommunityArticleDetail',
    params: { id: articleId }
  });
};
</script>

<template>
  <div>
    <van-tabs 
      v-model:active="active" 
      @change="handleTabChange"
      swipeable
      animated
    >
      <van-tab 
        v-for="item in tagList" 
        :key="item.id" 
        :title="item.name"
      >
        <div v-if="!loading">
          <div v-if="filteredArticles.length > 0">
            <div 
              v-for="article in filteredArticles" 
              :key="article.id" 
              class="item"
              @click="navigateToArticleDetail(article.id)"
            >
              <div class="header">
                <van-image round width="50" height="50"
                  :src="article.user?.avatar"
                />
                <p class="text">{{ article.user?.nickname }}</p>
              </div>
              <div class="content">
                <p>{{ article.content }}</p>
              </div>
              <div class="bottom">
                <van-button
                  class="action-btn"
                  :class="{ 'liked': article.isLike }"
                  :icon="article.isLike ? 'like' : 'like-o'"
                  :type="article.isLike ? 'danger' : 'default'"
                  size="small"
                  plain
                  @click.stop="handleLikeToggle(article, $event)"
                >
                  {{ article.likeCount || '0' }}
                </van-button>

                <van-button
                  class="action-btn"
                  icon="comment-o"
                  size="small"
                  plain
                  @click.stop="goToComments(article.id, $event)"
                >
                  {{ article.commentCount || '0' }}
                </van-button>
                
                <van-button
                  class="action-btn"
                  icon="share-o"
                  size="small"
                  plain
                >
                  分享
                </van-button>
              </div>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>暂无文章</p>
          </div>
        </div>
        <div v-else class="loading-state">
          <van-loading type="spinner" size="24px">加载中...</van-loading>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<style scoped>
.item {
  background-color: white;
  margin: 3%;
  border-radius: 15px;
  padding: 3%;
}

.header {
  display: flex;
  align-items: center;
}

.text {
  margin-left: 3%;
  font-weight: bold;
}

.content {
  margin: 10px 0;
}

.bottom {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.action-btn {
  flex: 1;
  margin: 0 4px;
}

.action-btn.liked {
  color: #ee0a24;
}

.empty-state, .loading-state {
  text-align: center;
  padding: 20px 0;
  color: #999;
}
</style>